﻿//文件指定编译编码UTF-8
#pragma execution_character_set("utf-8")

/**
*    @file:    httpservice.cpp
*    @brief:
*    @author:  sanshi522@163.com
*    @date:    2024-12-23  16:27
*/

#include "httpservice.h"
#include "requestmapper.h"

#include <QCoreApplication>
#include <QSettings>
#include <menuvo.h>
#include <metavo.h>
#include <authoritycontroller.h>
#include <menucontroller.h>
#include <rolecontroller.h>
#include <user.h>
#include <role.h>
#include <authority.h>
#include "usercontroller.h"
#include "authcontroller.h"
#include "coredatabase.h"

QMutex HttpService::mutex;
HttpService* HttpService::instance = nullptr;


HttpService *HttpService::getInstance()
{
    if (instance == nullptr) {
        QMutexLocker locker(&mutex);
        if (instance == nullptr) {
            instance = new HttpService();
        }
    }
    return instance;
}

void HttpService::deleteInstance()
{
    if (instance != nullptr) {
        delete instance;
        instance = nullptr;
    }
}

HttpService::HttpService(QObject *parent) : QObject(parent)
{
    qDebug() << __FUNCTION__;
    //注册类型
    qRegisterMetaType<int8_t>("int8_t");
    qRegisterMetaType<uint8_t>("uint8_t");
    qRegisterMetaType<int16_t>("int16_t");
    qRegisterMetaType<uint16_t>("uint16_t");
    qRegisterMetaType<int32_t>("int32_t");
    qRegisterMetaType<uint32_t>("uint32_t");
    qRegisterMetaType<int64_t>("int64_t");
    qRegisterMetaType<uint64_t>("uint64_t");
    requestMapper = new RequestMapper(this);

    installController("user", new UserController(this));
    installController("auth", new AuthController(this));
    installController("menu", new MenuController(this));
    installController("role", new RoleController(this));
    installController("authority", new AuthorityController(this));

    QSqlDatabase db = CoreDatabase::getInstance()->getConnection();

    QSqlQuery query(db);
    //===================================================创建用户表
    User user;
    if(!query.exec(user.generateCreateTableSql(db.driverName()))){
        qCritical() << query.lastError().text();
    }
    //----插入默认数据
    user.setId(1);
    user.setUsername("yanlei");
    user.setRealName("颜磊");
    user.setPassword("123456");
    user.setGender("男");
    user.setStatus(USER_STATUS_ENABLED);//状态启用
    user.setRoles(QStringList("admin"));
    query.exec(user.generateInsertSql());

    //===================================================创建角色表
    Role role;
    if(!query.exec(role.generateCreateTableSql(db.driverName()))){
        qCritical() << query.lastError().text();
    }
    role.clear();
    //----插入默认数据
    role.setId(1);
    role.setName("管理员");
    role.setCode("admin");
    role.setStatus(1);
    role.setDescription("管理员角色");
    query.exec(role.generateInsertSql());
    role.setId(2);
    role.setName("访客");
    role.setCode("guest");
    role.setStatus(1);
    role.setDescription("访客角色");
    query.exec(role.generateInsertSql());
//    //===================================================创建权限表
//    Authority authority;
//    if(!query.exec(query.exec(authority.generateCreateTableSql())){
//        qCritical() << query.lastError().text();
//    }

    //===================================================创建菜单表
    Menu menu;
    if(!query.exec(menu.generateCreateTableSql(db.driverName()))){
        qCritical() << query.lastError().text();
    }
    //----插入默认数据
    menu = Menu(10000,"System","/system","","BasicLayout",0,"",999,"系统管理",{"admin"});
    query.exec(menu.generateInsertSql());
    //系统
    menu = Menu(100001,"User","/user","","/core/user/index",10000,"",1,"用户",{"admin"});
    query.exec(menu.generateInsertSql());
    menu = Menu(100002,"Role","/role","","/core/role/index",10000,"",2,"角色",{"admin"});
    query.exec(menu.generateInsertSql());
//    menu = Menu(100003,"Authority","/authority","","/core/authority/index",10000,"",3,"权限",{"admin"});
//    query.exec(menu.generateInsertSql());
    menu = Menu(100004,"Menu","/menu","","/core/menu/index",10000,"",4,"菜单",{"admin"});
    query.exec(menu.generateInsertSql());

    CoreDatabase::getInstance()->releaseConnection(db);
    open();
}

HttpService::~HttpService()
{
    close();
    CoreDatabase::deleteInstance();
    qDebug() << __FUNCTION__;
}

HttpSessionStore *HttpService::getHttpSessionStore() const
{
    return httpSessionStore;
}

void HttpService::installController(QString path, HttpRequestHandler *httpRequestHandler)
{
   requestMapper->installController(path,httpRequestHandler);
}

void HttpService::open()
{
    QString configFileName = QCoreApplication::applicationDirPath() + "/config/httpservice.ini";
//    Configure logging into a file
    QSettings *logSettings = new QSettings(configFileName, QSettings::IniFormat, this);
    logSettings->beginGroup("logging");
    logger = new FileLogger(logSettings, 10000, this);

#ifndef QT_DEBUG
    logger->installMsgHandler();
#endif

    // Configure session store
    QSettings *sessionSettings = new QSettings(configFileName, QSettings::IniFormat, this);
    sessionSettings->beginGroup("sessions");
    httpSessionStore = new HttpSessionStore(sessionSettings, this);

    // Configure static file controller
//    QSettings *fileSettings = new QSettings(configFileName, QSettings::IniFormat, this);
//    fileSettings->beginGroup("docroot");
//    staticFileController = new StaticFileController(fileSettings, this);

    // Configure and start the TCP listener
    QSettings *listenerSettings = new QSettings(configFileName, QSettings::IniFormat, this);
    listenerSettings->beginGroup("listener");

    httpListener = new HttpListener(listenerSettings, requestMapper, this);
}

void HttpService::close()
{
    delete httpListener;
    delete requestMapper;
    delete httpSessionStore;
    logger->clear();
    delete logger;
}
